#include "../include/clientQueue.h"
int init_clientQueue(clientQueue_t *pclientQueue)
{   
    pclientQueue->timer = 0;//时间轮起始位置
    memset(pclientQueue->client, -1, sizeof(pclientQueue->client));//初始客户端数组
    memset(pclientQueue->index, -1, sizeof(pclientQueue->index));//每个客户不在时间轮中
    for(int i = 0; i < TIME_SLICE; ++i)// 结构体数组初始化
    {
        pclientQueue->time_out[i].head = NULL;
        pclientQueue->time_out[i].tail = NULL;
        pclientQueue->time_out[i].size = 0;
    }
}
//将新的客户端连接netfd以尾插法添加到时间轮pclientQueue的指定槽位，并记录其位置和超时时间
int fdAdd(int netfd, clientQueue_t *pclientQueue)// 尾插法
{   
    //如果已存在于时间轮中，先删除原位置
    if(pclientQueue->index[netfd]!=-1){
        fdDel(netfd,pclientQueue);
    }
    slotNode_t *newSlot = (slotNode_t *)calloc(1, sizeof(slotNode_t));//初始化
    newSlot->netfd = netfd;
    //记录这个连接放在哪个位置，方便后续删除或者更新
    pclientQueue->index[netfd] = (pclientQueue->timer + TIME_SLICE - 1) % TIME_SLICE;// 加入时有TIME_SLICE的时间，timer是下一次要检查的地方
    int index = (pclientQueue->timer + TIME_SLICE - 1) % TIME_SLICE;//确定这个连接被放在哪一时间片
    ++pclientQueue->time_out[index].size;//增加连接数量
    if(pclientQueue->time_out[index].head == NULL)//当前槽位为空，没有连接
    {   //新节点
        pclientQueue->time_out[index].head = newSlot;
        pclientQueue->time_out[index].tail = newSlot;
    }
    else
    {   //有连接，尾插
        pclientQueue->time_out[index].tail->next = newSlot;
        //更新tail
        pclientQueue->time_out[index].tail = newSlot;
    }
}
//从时间轮pclientQueue中查找并删除指定的客户端连接netfd，释放对应节点内存并更新链表结构。
int fdDel(int netfd, clientQueue_t *pclientQueue)
{
    int index = pclientQueue->index[netfd];//获取当前netfd所在槽位索引
    pclientQueue->index[netfd] = 0;// 从时间轮移除
    slotNode_t *cur = pclientQueue->time_out[index].head;//从链表头节点开始查找
    slotNode_t *pre = cur;
    if(cur == NULL)// 当前槽位为空
    {
        return 0;
    }
    if(cur->netfd == netfd)//要删除的节点是头节点
    {
        pclientQueue->time_out[index].head = cur->next;
        free(cur);
        --pclientQueue->time_out[index].size;
    }
    else
    {
        while(cur != NULL)
        {
            if (cur->netfd == netfd)//找到目标节点
            {
                pre->next = cur->next;
                free(cur);
                --pclientQueue->time_out[index].size;
                break;
            }
            pre = cur;
            cur = cur->next;
        }
    }
}

